package com.jubaozan.framework.sentinel.stat.traffic.repository;

import com.jubaozan.framework.sentinel.stat.traffic.TrafficLogSecondCache.TrafficLog;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/7/23 18:50
 */

@Slf4j
@Repository
public class TrafficLogMysql implements TrafficLogRepository {

    @Resource
    private JdbcTemplate jdbcTemplate;

    private static final String INSERT_SQL = "INSERT INTO sentinel_traffic_second_log " +
        "(timestamp, ip, app, resource, total_count, success_count, exception_count, total_rt) " +
        "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

    public void batchSave(List<TrafficLog> logs) {
        jdbcTemplate.batchUpdate(INSERT_SQL, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                TrafficLog log = logs.get(i);
                ps.setTimestamp(1, new java.sql.Timestamp(log.getTimestamp().getTime()));
                ps.setString(2, log.getIp());
                ps.setString(3, log.getApp());
                ps.setString(4, log.getResource());
                ps.setInt(5, log.getTotalCount());
                ps.setInt(6, log.getSuccessCount());
                ps.setInt(7, log.getExceptionCount());
                ps.setDouble(8, log.getTotalRt());
            }

            @Override
            public int getBatchSize() {
                return logs.size();
            }
        });
    }
}
